# -*- coding: UTF-8 -*-
# 增加记录
import docx
from docx import Document        #导入读取word模块
import os
import os.path
from pythonwin import win32ui    #导入打开文件选择框模块
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.shared import Cm
import re
import win32com
from win32com.client import Dispatch
from win32com import client as wc

#class Word():
input('选择产品验证方案-回车继续')
word = wc.gencache.EnsureDispatch('Word.Application')
dlg = win32ui.CreateFileDialog(1)         #1表示打开文件对话框
dlg.SetOFNInitialDir('C:/Users')          #设置打开文件对话框中的初始显示目录
dlg.DoModal()
programe_word = dlg.GetPathName()               #获取选择的文件名称
Path_l = os.path.join(os.path.dirname(programe_word))
print("文件所在目录："+ Path_l)
print("文件地址："+ programe_word)
Path = os.path.join(os.getcwd(),programe_word)    #获取选择的文件路径
record_path = Path_l + '\记录文档'+'.docx'

num_start = int(input("请输入你想从第几个表格开始拉取数据："))
num_start2 = num_start - 1
document = Document(programe_word) #读入文件
programe_tables = document.tables #获取文件中的表格集
programe_table_num=len(programe_tables)#获取文档的表格个数
print("此文档表格个数:"+str(programe_table_num))

rows_1 = 9 # 方案步骤上方固定行数
rows_2 = 3 # 方案步骤下方固定行数、记录步骤上方固定行数
rows_3 = 4 # 记录步骤下方固定行数
rows_4 = 9+3+4 # 总和

num3 = input("请输入您想要跳过的表格,回车\n（暂未开发，请输入大写的NO）:")
print(num3)
if num3 == 'NO':
    for k in range(num_start2,programe_table_num):  # programe_table_num
        '''记录表格行添加'''
        table = programe_tables[k] # 获取第二个表格对象
        table_rows = len(table.rows)
        table_columns = len(table.columns)
        table_rows_add = table_rows-rows_1
        print("表格"+str(k+1)+"的行数:"+ str(len(table.rows))  + "     列数：" + str(len(table.columns)))# 打印表格k的行列数
        try:
            document.tables[k].add_row()    #记录及判决结果
            document.tables[k].add_row()    #样品追溯
            document.tables[k].add_row()    #序号
            for i in range(table_rows_add): #加步骤
                document.tables[k].add_row() # 表格最下方增加一行
            document.tables[k].add_row()    #附录
            document.tables[k].add_row()    #备注
            document.tables[k].add_row()    #记录人
            document.tables[k].add_row()    #校对人
        except Exception:
            print("添加记录行失败")

        '''合并单元格'''
        try:
            End_columns = table_columns-1
            def mer(row_star,row_end,coun_star,coun_end):   # 封装合并单元格方法
                a = table.cell(row_star, coun_star)	# 获取左上单元格
                b = table.cell(row_end, coun_end)   # 获取右下单元格
                a.merge(b)   # 合并单元格

            one = table_rows
            mer(one,one,0,End_columns) # 合并记录及判决结果行
            two = table_rows+1
            mer(two,two,1,End_columns) # 合并追溯行
            three = table_rows+2
            mer(three,three,1,4) # 合并序号行
            for o in range(table_rows_add): # 合并步骤行
                four = table_rows + 3 + o
                mer(four,four,1,4) 
            five = table_rows+3+table_rows_add  
            mer(five,five,0,End_columns) # 合并附录行
            six = table_rows+3+table_rows_add+1
            mer(six,six,0,End_columns) # 合并备注行 
            seven = table_rows+3+table_rows_add+2
            mer(seven,seven,0,1) # 合并记录人
            mer(seven,seven,2,4) # 合并记录人
            eight = table_rows+3+table_rows_add+3
            mer(eight,eight,0,1) # 合并校对人 
            mer(eight,eight,2,4) # 合并校对人
        except Exception:
            print("合并单元格失败")

        '''输入内容'''
        try:
            def bc(ro,co,te):   # 封装居中加粗方法
                run = table.cell(ro, co).paragraphs[0].add_run(te)
                run.font.bold = True
                table.cell(ro, co).paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER

            
            bc(one,0,'记录及判决结果')
            bc(two, 0,'样品追溯')
            bc(three, 0,'序号')
            bc(three, 2,'记录')
            bc(three, 5,'判决')
        except Exception:       
            print("输入内容失败1")

        for j in range(table_rows_add): #加步骤
            try:
                four = table_rows + 3 + j
                table.cell(four, 0).text = str(j+1)
            except Exception:
                print("输入步骤文字失败")

        try:
            bc(five, 0,'附录')
            table.cell(seven, 0).text = '记录人:'
            # table.cell(seven,0).width=Cm(5)
            table.cell(six, 0).paragraphs[0].add_run('备注：\n \n')
            table.cell(seven, 2).text = '签名:'
            table.cell(seven, End_columns).text = '时间:'
            table.cell(eight, 0).text = '校对人:'
            # table.cell(eight,0).width=Cm(4.25)
            table.cell(eight, 2).text = '签名:'
            table.cell(eight, End_columns).text = '时间:'
        except Exception:
            print("输入内容失败2")

        try:    
            def _set_cell_background(cell, fill, color=None, val=None): # 封装单元格元素方法

                from docx.oxml.shared import qn  # feel free to move these out
                from docx.oxml.xmlchemy import OxmlElement

                cell_properties = cell._element.tcPr
                try:
                    cell_shading = cell_properties.xpath('w:shd')[0]  # in case there's already shading
                except IndexError:
                    cell_shading = OxmlElement('w:shd') # add new w:shd element to it
                if fill:
                    cell_shading.set(qn('w:fill'), fill)  # set fill property, respecting namespace
                if color:
                    pass # TODO
                if val:
                    pass # TODO
                cell_properties.append(cell_shading)  # finally extend cell props with shading element
            _set_cell_background(table.rows[one].cells[0], '#d9d9d9')
        except Exception:
            print("填充单元格颜色失败")

        print("表格"+k+"添加完成")

else:
    print("真的没开发")

document.save(record_path) # 保存文档
input('已保存在在方案目录下《记录文档.docx》”  键入回车完成')